// src/components/ui-component/extended/DynamicFieldsAndChips.js
import React, { useEffect, useRef } from 'react';
import Chip from '@mui/material/Chip';
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';
import useDynamicElements from 'hooks/useDynamicElements';
import InputBase from '@mui/material/InputBase';
import Popper from '@mui/material/Popper';

const DynamicFieldsAndChips = () => {
  const initialElements = [
    { type: 'chip', label: '内容', content: 'test' },
    { type: 'chip', label: '内容2', content: 'test2' },
    { type: 'text', label: '', value: '' },
    { type: 'chip', label: '日期', content: '2021-10-10' },
    { type: 'chip', label: '日期2', content: '2021-10234-10' },
    { type: 'text', label: '输入框2', value: '' }
  ];

  const { elements, handleInputChange, removeElementByIndex, cursorPosition, setCursorPosition } = useDynamicElements(initialElements); // 新增：获取 cursorPosition 和 setCursorPosition
  const inputRefs = useRef([]); // 新增：用于保存输入框引用的 ref

  // 新增：设置光标位置
  useEffect(() => {
    if (cursorPosition !== null) {
      console.log('cursorPosition:', cursorPosition);
      inputRefs.current[cursorPosition]?.focus();
      setCursorPosition(null);
    }
  }, [cursorPosition, setCursorPosition]);

  const handleSummary = () => {
    let summary = '';
    elements.forEach((element) => {
      if (element.type === 'chip') {
        summary += `${element.content} `;
      }
      if (element.type === 'text') {
        summary += `${element.value} `;
      }
    });
    console.log('汇总内容:', summary);
  };

  const handleKeyDown = (e, index) => {
    console.log('index', index);
    if (index > 0 && e.target.selectionStart === 0 && e.key === 'Backspace') {
      removeElementByIndex(index - 1);
    }
  };

  return (
    <div>
      {elements.map((element, index) => {
        if (element.type === 'chip') {
          return <Chip key={index} label={element.label} />;
        }
        if (element.type === 'text') {
          return (
            <InputBase
              key={index}
              label={element.label}
              value={element.value}
              onChange={(e) => handleInputChange(e, index)}
              onKeyDown={(e) => handleKeyDown(e, index)}
              // inputRef={(el) => (inputRefs.current[index] = el)} // 新增：保存输入框的引用
            />
          );
        }
        return null;
      })}
      <Button onClick={handleSummary}>汇总</Button>
    </div>
  );
};

export default DynamicFieldsAndChips;
